package cn.wolfcode.service.impl;

import cn.wolfcode.domain.SystemDictionaryItem;
import cn.wolfcode.mapper.SystemDictionaryItemMapper;
import cn.wolfcode.query.QueryObject;
import cn.wolfcode.service.ISystemDictionaryItemService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SystemDictionaryItemServiceImpl implements ISystemDictionaryItemService {

    @Autowired
    private SystemDictionaryItemMapper systemDictionaryItemMapper;


    @Override
    public void save(SystemDictionaryItem systemDictionaryItem) {
        //要判断systemDictionaryItem中的sequence是否为空
        if (systemDictionaryItem.getSequence() == null) {
            //要去查询出当前明细表中所在的字典目录中的明细表中的最大sequence
            int maxSequence = this.selectMaxSequence(systemDictionaryItem.getParentId());
            //把最大的sequence+1之后设置给systemDictionaryItem对象
            systemDictionaryItem.setSequence(maxSequence+1);
        }
        systemDictionaryItemMapper.insert(systemDictionaryItem);
    }

    /**
     * 获取相同parentId(字典目录)下的sequence的最大值
     * @param parentId
     * @return
     */
    private int selectMaxSequence(Long parentId) {
        return systemDictionaryItemMapper.selectMaxSequence(parentId);
    }

    @Override
    public void delete(Long id) {
        systemDictionaryItemMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(SystemDictionaryItem systemDictionaryItem) {
        //要判断systemDictionaryItem中的sequence是否为空
        if (systemDictionaryItem.getSequence() == null) {
            //要去查询出当前明细表中所在的字典目录中的明细表中的最大sequence
            int maxSequence = this.selectMaxSequence(systemDictionaryItem.getParentId());
            //把最大的sequence+1之后设置给systemDictionaryItem对象
            systemDictionaryItem.setSequence(maxSequence+1);
        }
        systemDictionaryItemMapper.updateByPrimaryKey(systemDictionaryItem);
    }

    @Override
    public SystemDictionaryItem get(Long id) {
        return systemDictionaryItemMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<SystemDictionaryItem> listAll() {
        return systemDictionaryItemMapper.selectAll();
    }

    @Override
    public PageInfo<SystemDictionaryItem> query(QueryObject qo) {
        //当需要排序时,需要在传入一个排序的参数 asc表示升序,desc表示降序
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize(),"sequence asc"); //对下一句sql进行自动分页
        List<SystemDictionaryItem> systemDictionaryItems = systemDictionaryItemMapper.selectForList(qo); //里面不需要自己写limit
        return new PageInfo<>(systemDictionaryItems);
    }

    /**
     * 通过目录编码查询对应的明细
     * @param sn
     * @return
     */
    @Override
    public List<SystemDictionaryItem> selectByDicSn(String sn) {
        return systemDictionaryItemMapper.selectByDicSn(sn);
    }
}
